package com.shambles.weixin.controller;

import com.shambles.manage.mapper.MessageListMapper;
import com.shambles.manage.mapper.UsersMapper;
import com.shambles.manage.mapper.WeiXinMapper;
import com.shambles.manage.model.MessageList;
import com.shambles.manage.model.Users;
import com.shambles.manage.model.WeiXin;
import com.shambles.manage.service.UserService;
import com.shambles.manage.service.WeiXinService;
import com.shambles.weixin.MessageTemplate.ChatTemplateProcessor;
import com.shambles.weixin.MessageTemplate.TemplateData;
import com.shambles.weixin.MessageTemplate.WxTemplate;
import common.HttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/mobile/WechatSendMessage")
public class WechatSendMessageController {
    Integer campusId = 1;

    private WeiXinService weixinService;

    private UserService userService;

    @Autowired
    public void setAccessTokenService(WeiXinService weiXinService) {
        this.weixinService = weiXinService;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }


    @RequestMapping("/send")
    public @ResponseBody
    String template(HttpServletRequest request, HttpServletResponse response,
                    @RequestParam String title, @RequestParam String reportUser,
                    @RequestParam String reportContext, @RequestParam String place, @RequestParam String url) {
        String accessToken;
        WeiXin weixin;

        weixin = weixinService.getCampusById(campusId);
        accessToken = weixin.getAccessToken();

        List userlist = userService.getUserByGuidance();

        ChatTemplateProcessor wechatTemplate = new ChatTemplateProcessor();

        Iterator<Users> iterator = userlist.iterator();

        String message = "";

        while (iterator.hasNext()) {

            Users users = iterator.next();

            String openid = users.getOpenId();

            WxTemplate templateData = new WxTemplate();
            System.out.println("url=" + url);
            templateData.setUrl(url);
            templateData.setTouser(openid);
            templateData.setTopcolor("#000000");
            templateData.setTemplate_id("XjGvV8BcSYzVtcxOJmXD2VefRqor4QQXYfLabWckkiw");
            Map<String, TemplateData> m = new HashMap<String, TemplateData>();
            TemplateData first = new TemplateData();
            first.setColor("#000000");
            first.setValue(title);
            m.put("first", first);
            TemplateData keyword1 = new TemplateData();
            keyword1.setColor("#328392");
            keyword1.setValue(reportUser);
            m.put("keyword1", keyword1);
            TemplateData keyword2 = new TemplateData();
            keyword2.setColor("#328392");
            keyword2.setValue(reportContext);
            m.put("keyword2", keyword2);
            TemplateData keyword3 = new TemplateData();
            keyword3.setColor("#328392");
            keyword3.setValue(place);
            m.put("keyword3", keyword3);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();
            String time = sdf.format(date);
            TemplateData keyword4 = new TemplateData();
            keyword4.setColor("#328392");
            keyword4.setValue(time);
            m.put("keyword4", keyword4);
            TemplateData remark = new TemplateData();
            remark.setColor("#929232");
            remark.setValue("点击查看事件位置");
            m.put("remark", remark);
            templateData.setData(m);

            String s = wechatTemplate.sendTemplateMessage(accessToken, templateData);

            message = message + "  " + users.getNickname() + "  " + s;

            MessageList messageList = new MessageList();

            messageList.setCampusId(campusId);
            messageList.setOpenId(openid);
            messageList.setContext(reportContext);
            messageList.setType("紧急报告");
            messageList.setSendTime(date);
            if (s.equals("消息发送成功")) {
                messageList.setState(1);
            } else {
                messageList.setState(0);
            }

            weixinService.insertMessageList(messageList);

        }

        return message;

    }


    public void send(@RequestParam String guid, @RequestParam String hidden_GUID) {


    }


    public void sendMessage(@RequestParam Integer place, @RequestParam String Template_Id,
                            @RequestParam String Send_Type, @RequestParam String url,
                            @RequestParam String first_data, @RequestParam String keyword1_data,
                            @RequestParam String keyword2_data, @RequestParam String keyword3_data,
                            @RequestParam String keyword4_data, @RequestParam String remark_data) {

        Integer campusId = 1;

        String accessToken;
        WeiXin weixin;

        try {

            ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-mybatis2.xml");
            DefaultSqlSessionFactory defaultSqlSessionFactory = (DefaultSqlSessionFactory) applicationContext.getBean("sqlSessionFactory");
            SqlSession sqlSession = defaultSqlSessionFactory.openSession();

            UsersMapper usersMapper = sqlSession.getMapper(UsersMapper.class);

            MessageListMapper messageListMapper = sqlSession.getMapper(MessageListMapper.class);

            List<Users> list = usersMapper.getUserByPlace(place);

            if (list != null) {

                Iterator<Users> iterator = list.iterator();

                while (iterator.hasNext()) {

                    Users users = iterator.next();

                    if (users == null) {
                        return;
                    }

                    String openId = users.getOpenId();

                    WeiXinMapper weiXinMapper = sqlSession.getMapper(WeiXinMapper.class);

                    weixin = weiXinMapper.getCampus(campusId);
                    accessToken = weixin.getAccessToken();

                    WxTemplate templateData = new WxTemplate();
                    templateData.setUrl(url);
                    templateData.setTouser(openId);
                    templateData.setTopcolor("#000000");
                    templateData.setTemplate_id(Template_Id);
                    Map<String, TemplateData> m = new HashMap<String, TemplateData>();
                    TemplateData first = new TemplateData();
                    first.setColor("#000000");
                    first.setValue(first_data);
                    m.put("first", first);

                    TemplateData keyword1 = new TemplateData();
                    keyword1.setColor("#328392");
                    keyword1.setValue(keyword1_data);
                    m.put("keyword1", keyword1);
                    TemplateData keyword2 = new TemplateData();
                    keyword2.setColor("#328392");
                    keyword2.setValue(keyword2_data);
                    m.put("keyword2", keyword2);
                    TemplateData keyword3 = new TemplateData();
                    keyword3.setColor("#328392");
                    keyword3.setValue(keyword3_data);
                    m.put("keyword3", keyword3);

                    if (keyword4_data != null && !keyword4_data.equals("")) {
                        TemplateData keyword4 = new TemplateData();
                        keyword4.setColor("#328392");
                        keyword4.setValue(keyword4_data);
                        m.put("keyword4", keyword4);
                    }

                    if (remark_data != null && remark_data.equals("")) {
                        TemplateData remark = new TemplateData();
                        remark.setColor("#929232");
                        remark.setValue(remark_data);
                        m.put("remark", remark);
                    }
                    templateData.setData(m);

                    ChatTemplateProcessor wechatTemplate = new ChatTemplateProcessor();

                    String s = wechatTemplate.sendTemplateMessage(accessToken, templateData);

                    MessageList messageList = new MessageList();

                    messageList.setCampusId(campusId);
                    messageList.setOpenId(openId);
                    messageList.setContext(keyword1_data + "," + keyword2_data +
                            "," + keyword3_data + "," + keyword4_data);
                    messageList.setType(Send_Type);
                    messageList.setSendTime(new Date());
                    if (s.equals("消息发送成功")) {
                        messageList.setState(1);
                    } else {
                        messageList.setState(0);
                    }

                    messageListMapper.insertMessageList(messageList);
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    /**
     * 通过openId发送消息
     *
     * @param openId
     * @param Template_Id
     * @param Send_Type
     * @param url
     * @param first_data
     * @param keyword1_data
     * @param keyword2_data
     * @param keyword3_data
     * @param keyword4_data
     * @param remark_data
     */
    public Integer sendMessage2(@RequestParam String openId, @RequestParam String Template_Id,
                                @RequestParam String Send_Type, @RequestParam String url,
                                @RequestParam String first_data, @RequestParam String keyword1_data,
                                @RequestParam String keyword2_data, @RequestParam String keyword3_data,
                                @RequestParam String keyword4_data, @RequestParam String remark_data) {

        Integer campusId = 1;
        Integer res=0;
        String accessToken;
        WeiXin weixin;

        try {

            ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-mybatis2.xml");
            DefaultSqlSessionFactory defaultSqlSessionFactory = (DefaultSqlSessionFactory) applicationContext.getBean("sqlSessionFactory");
            SqlSession sqlSession = defaultSqlSessionFactory.openSession();

            UsersMapper usersMapper = sqlSession.getMapper(UsersMapper.class);

            WeiXinMapper weiXinMapper = sqlSession.getMapper(WeiXinMapper.class);

            weixin = weiXinMapper.getCampus(campusId);
            accessToken = weixin.getAccessToken();

            WxTemplate templateData = new WxTemplate();
            templateData.setUrl(url);
            templateData.setTouser(openId);
            templateData.setTopcolor("#000000");
            templateData.setTemplate_id(Template_Id);
            Map<String, TemplateData> m = new HashMap<String, TemplateData>();
            TemplateData first = new TemplateData();
            first.setColor("#000000");
            first.setValue(first_data);
            m.put("first", first);

            TemplateData keyword1 = new TemplateData();
            keyword1.setColor("#328392");
            keyword1.setValue(keyword1_data);
            m.put("keyword1", keyword1);
            TemplateData keyword2 = new TemplateData();
            keyword2.setColor("#328392");
            keyword2.setValue(keyword2_data);
            m.put("keyword2", keyword2);
            TemplateData keyword3 = new TemplateData();
            keyword3.setColor("#328392");
            keyword3.setValue(keyword3_data);
            m.put("keyword3", keyword3);

            if (keyword4_data != null && !keyword4_data.equals("")) {
                TemplateData keyword4 = new TemplateData();
                keyword4.setColor("#328392");
                keyword4.setValue(keyword4_data);
                m.put("keyword4", keyword4);
            }

            if (remark_data != null && remark_data.equals("")) {
                TemplateData remark = new TemplateData();
                remark.setColor("#929232");
                remark.setValue(remark_data);
                m.put("remark", remark);
            }
            templateData.setData(m);

            ChatTemplateProcessor wechatTemplate = new ChatTemplateProcessor();

            String s = wechatTemplate.sendTemplateMessage(accessToken, templateData);
            if (s.equals("消息发送成功")) {
                res = 1;
            } else {
                res = 0;
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return res;
    }

    //发送短信验证码
    public Integer sendPhoneMessage(String phone,String Message,
                                    String charter,String openId){

        Integer campusId=1;

        HttpClient httpClient = new HttpClient();

        String requestUrl="http://utf8.api.smschinese.cn";

        List<BasicNameValuePair> reqParam = new ArrayList<BasicNameValuePair>();
        reqParam.add(new BasicNameValuePair("Uid", "龙驰资产管理公司"));
        reqParam.add(new BasicNameValuePair("Key", "d41d8cd98f00b204e980"));
        reqParam.add(new BasicNameValuePair("smsMob", phone));
        reqParam.add(new BasicNameValuePair("smsText", Message));
        String r = httpClient.doGet(requestUrl, reqParam);
        return Integer.parseInt(r);
    }


    public Integer getPhoneMessageNumber(){

        HttpClient httpClient = new HttpClient();

        String requestUrl="http://www.smschinese.cn/web_api/SMS";

        List<BasicNameValuePair> reqParam = new ArrayList<BasicNameValuePair>();
        reqParam.add(new BasicNameValuePair("Action", "SMS_Num"));

//        reqParam.add(new BasicNameValuePair("Uid", "兴泸资产管理有限公司"));
//        reqParam.add(new BasicNameValuePair("Key", "d41d8cd98f00b204e980"));
        reqParam.add(new BasicNameValuePair("Uid", "龙驰资产管理公司"));
        reqParam.add(new BasicNameValuePair("Key", "d41d8cd98f00b204e980"));
        String r=httpClient.doGet(requestUrl, reqParam);

        return Integer.parseInt(r);

    }

    /**
     * 注册会员短信发送验证码
     */
    @GetMapping(value = "/sendMessageCode")
    public String sendMessageCode(String phone) throws UnsupportedEncodingException {

        HttpClient httpClient = new HttpClient();

        //随机验证码
        String vcode = "";
        for (int i = 0; i < 6; i++) {
            vcode = vcode + (int) (Math.random() * 9);
        }

        //发送信息的内容
        String Message = "#您正在进行手机验证,验证码是:"+vcode+",5分钟内有效";

        //组装电话号码及内容然后urlencoder
        String phoneContent=phone+Message;
        String phoneContents=java.net.URLEncoder.encode(phoneContent, "UTF-8");

        //短信发送调用URL
        String url="http://113.125.24.16:7862/sms?action=p2p&rt=json&account=800489&password=123456&mobileContentList="+phoneContents+"&extno=10690489";

        httpClient.doPost(url,null);

        return String.valueOf("OK");
    }

}
